<%@page import="com.sun.faces.facelets.tag.jstl.core.ForEachHandler"%>
<%@page import="com.mysql.jdbc.StringUtils"%>
<%@ page language="java" import="java.sql.*" %>
<%@ page import="java.io.*,java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat" %>
<%@ page import="java.util.List"%>  
<%@ page import="java.util.Iterator"%>  
<%@ page import="org.apache.commons.fileupload.*"%>  
<%@ page import="org.apache.commons.fileupload.disk.*"%>  
<%@ page import="org.apache.commons.fileupload.servlet.*"%> 

<%
    String driver = "org.gjt.mm.mysql.Driver";
    Class.forName(driver).newInstance();

    Connection con=null;
    ResultSet rst=null;
    Statement stmt=null;

    try{
            String url="jdbc:mysql://localhost:3306/progin_171_13509008?user=root";
            con=DriverManager.getConnection(url);
            stmt=con.createStatement();
    }
    catch(Exception e){
            System.out.println(e.getMessage());
    }
%>

<% 
    // get User Name From session
    String userPosting = (String)(session.getAttribute("user_name"));
%>
    <p><%= session.getAttribute("user_name")%></p>
<%  
    // get next id_content for image naming
    int curIDContent =0 ;
    rst=stmt.executeQuery("SELECT MAX(id_content) as id FROM content");
    while (rst.next()){
        curIDContent = Integer.parseInt(rst.getString("id"));
    }
    curIDContent++;
%>

<%!	  
//Uploading File -- method to return file extension  
String getFileExt(String xPath){  

    //Find extension  

    int dotindex = 0;	//extension character position  
    dotindex = xPath.lastIndexOf('.');  

    if (dotindex == -1){	// no extension	  
        return "";  
    }  

    int slashindex = 0;	//seperator character position  
    slashindex = Math.max(xPath.lastIndexOf('/'),xPath.lastIndexOf('\\'));  

    if (slashindex == -1){	// no seperator characters in string  
        return xPath.substring(dotindex);  
    }  

    if (dotindex < slashindex){	//check last "." character is not before last seperator  
        return "";  
    }  
    return xPath.substring(dotindex);  
}
%>

<%  
    // Form Processing
    //get form value
/*    String optionResult = request.getParameter("optionResult");
    String titleContent = request.getParameter("titleContent");
    String linkURL = request.getParameter("linkURL");
    String linkDescription = request.getParameter("linkDescription");
    String videoContent = request.getParameter("videoContent");
    String tagContent = request.getParameter("tagContent");
    String pathFile = request.getParameter("pathFile");
*/

    String optionResult = request.getParameter("option");
    String titleContent = request.getParameter("title");
    String linkURL = request.getParameter("link_url");
    String linkDescription = request.getParameter("link_description");
    String videoContent = request.getParameter("mov");
    String tagContent = request.getParameter("tag");
    boolean boolPass = false; // boolean for last process
    String pathFile = (String)(session.getAttribute("path"));

    // Get current datetime
    java.util.Date now = new java.util.Date();
    String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
    String strDateNew = sdf.format(now) ;
             
    if(optionResult != null ){
        // Content == link
        if (optionResult.equals("link")){
            if (titleContent.isEmpty()){
                out.println("Judul belum terisi.</br>");
            }
            else if (linkURL.isEmpty()){
                out.println("Url link belum terisi.</br>");
            }
            else if(linkDescription.isEmpty()){
                out.println("Deskripsi Link belum terisi.</br>");
            }
            else {
                

                // user diambil dari session
                String sqlInsertLinkContent = "INSERT INTO content (title, content_type, content_filled, content_description, posting_time, user_name) VALUES ('"+titleContent+"', '"+optionResult+"', '"+linkURL+"' ,'"+linkDescription+"', '"+strDateNew+"', '"+userPosting+"')";
                try{ 
                    int i;
                    i = stmt.executeUpdate(sqlInsertLinkContent);
                } catch (SQLException e){
                    out.println("Caught SQL Exception: " + e);
                }
                out.println("Link Posted!");
                boolPass = true;
            }
        }
         
        // content_type = video
        if (optionResult.equals("video")){
            if (titleContent.isEmpty()){
                out.println("Judul belum terisi.</br>");
            }
            if (videoContent.isEmpty()){
                out.println("Video Url belum terisi.</br>");
            }
            else {
                // !! nanti user diambil dari session
                String sqlInsertVideoContent = "INSERT INTO content (title, content_type, content_filled, content_description, posting_time, user_name) VALUES ('"+titleContent+"', '"+optionResult+"', '"+videoContent+"' ,'','"+strDateNew+"', '"+userPosting+"')";
                try{ 
                    int j;
                    j = stmt.executeUpdate(sqlInsertVideoContent);
                } catch (SQLException e){
                    out.println("Caught SQL Exception: " + e);
                }
                out.println("Video Posted!");
                boolPass = true;
            }
        }
        if (optionResult.equals("image")){
            if (titleContent.isEmpty()){
                out.println("Judul belum terisi.</br>");
            }
            if (pathFile.isEmpty()){
                out.println("Please Upload Image First!</br>");
            }
            else {
                // !! nanti user diambil dari session
                String queryInsertImage = "INSERT INTO content (title, content_type, content_filled,content_description, posting_time, user_name) VALUES ('"+titleContent+"', '"+optionResult+"','"+pathFile+"', '', '"+strDateNew+"', '"+userPosting+"')";
                try{ 
                    int j;
                    j = stmt.executeUpdate(queryInsertImage);
                } catch (SQLException e){
                    out.println("Caught SQL Exception: " + e);
                }
                out.println("Image Posted!");
                boolPass = true;
            }
        }
    }
 

    //check existing tag and insert new tag, tag_content
    if(boolPass == true){
        // parse tag content
        String [] tagArray = tagContent.split(",");
        // remove space
        int i=0;
        for(i=0; i<tagArray.length ;i++) {
            tagArray[i]= tagArray[i].trim();
        }
        // return $tagArray as result for tag input, check on database
        //get current tag on database
        String querySelectTag = "select tag_name from tag";
        try{ 
            rst = stmt.executeQuery(querySelectTag);
        } catch (SQLException e){
            out.println("Caught SQL Exception: " + e);
        }

        //create currentTagOnDatabase= list of tag yang sudah ada di database
        int totalRowResult;
        totalRowResult = 0;
        while (rst.next()){
            totalRowResult++;
        }
        String[] currentTagOnDatabase=new String[totalRowResult];
        int j;  //counter
        j=0;
        try{ 
            rst = stmt.executeQuery(querySelectTag);
        } catch (SQLException e){
            out.println("Caught SQL Exception: " + e);
        }
        while (rst.next()){
            currentTagOnDatabase[j]= rst.getString("tag_name");
            j++;
        }
        
        // cross check data and insert tag
        int countCurDataTag= currentTagOnDatabase.length;
        int countTagArray = tagArray.length;

        boolean isExist = false;
        j=0;
        i=0;
        for (j = 0 ; j < countTagArray; j++){
            for (i=0; i< countCurDataTag; i++){
                if(tagArray[j].equals(currentTagOnDatabase[i])){
                    // if we found same data on database, set element with undefined value
                    tagArray[j]= "9999";
                }
            }
        }
        int k;
        k=0;
        // $tagArray with value = 9999 is not valid
        for (k= 0; k < countTagArray; k++){
        // input tag valid, insert into database
            if(tagArray[k]!= "9999" && tagArray[k]!=""){
                String q1 = "INSERT INTO tag (tag_name) VALUES ('"+tagArray[k]+"')";
                try{ 
                    int o;
                    o = stmt.executeUpdate(q1);
                } catch (SQLException e){
                    out.println("Caught SQL Exception: " + e);
                }
                
                //get id_tag which have just inserted
                String q2 = "select id_tag from tag where tag_name ='"+tagArray[k]+"'";
                try{ 
                    rst = stmt.executeQuery(q2);
                } catch (SQLException e){
                    out.println("Caught SQL Exception: " + e);
                }
                
                int idTagNew = 0;
                while (rst.next()){
                    idTagNew = Integer.parseInt(rst.getString("id_tag"));
                }
                //insert into tag relation with content
                String q3 = "Insert Into tag_content(id_tag, id_content) VALUES( "+idTagNew+","+curIDContent+")";
                try{ 
                    int o;
                    o = stmt.executeUpdate(q3);
                } catch (SQLException e){
                    out.println("Caught SQL Exception: " + e);
                }
            }
        }
        
        // Check for achievement
        // get next id_content for image naming
        String totalPosting = "";

        try{ 
            rst = stmt.executeQuery("select count(*) as totalPosting from content where user_name ='"+userPosting+"'");
        } catch (SQLException e){
            out.println("Caught SQL Exception: " + e);
        }
        while (rst.next()){
            totalPosting = rst.getString("totalPosting");
        }

        if (totalPosting.equals("1")){
            //Insert Achievement ke user
            try{ 
                int o;
                o = stmt.executeUpdate("Insert into user_achievement (user_name, id_achievement) VALUES ('"+userPosting+"',1) ");
            } catch (SQLException e){
                out.println("Caught SQL Exception: " + e);
            }
        }
        if (totalPosting.equals("10")){
            //Insert Achievement ke user
            try{ 
                int o;
                o = stmt.executeUpdate("Insert into user_achievement (user_name, id_achievement) VALUES ('"+userPosting+"',2) ");
            } catch (SQLException e){
                out.println("Caught SQL Exception: " + e);
            }
        }
        
        // testing session untuk detail
        session.setAttribute("user_name", "robert");
        //$_SESSION['user_name']='robert';

        //redirect to detil content
        session.setAttribute("id_content", curIDContent);
        //$_SESSION['id_content']=$curIDContent;
        out.println("<input type=\"hidden\" name=\"redirect\" value=\"detail.jsp\">");
                                           
        //posting success, redirect to detail content
        response.sendRedirect("detail.jsp");
    }
%>